using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Logic;
using NetProtocol.POD;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public partial class FakeDataCenter : Singleton<FakeDataCenter>
    {
        private static readonly string tempSavePath;

        public long playerId => GameDataCenter.PlayerData != null ? GameDataCenter.PlayerData.pid : 1;
        public string gameServerId => GameDataCenter.PlayerData != null ? GameDataCenter.PlayerData.gameServerId : "0";

        public int levelCid { get; set; } = 101;
        public bool isLocalLevel { get; set; } = true;

        public CreateLevelPOD levelPOD { get; set; }
        public LevelSavePOD levelSavePOD { get; set; }

        static FakeDataCenter()
        {
            tempSavePath = Application.dataPath + "/ToolApp/Script/Editor/LevelMapEditor/Config/TempLvSave.json";
        }

#if UNITY_EDITOR
        [MenuItem("ToolApp/关卡编辑器/保存/临时保存", false, 9)]
        private static void TemplateSave()
        {
            if (Application.isPlaying)
            {
                LevelSavePOD pod = SLevelLogicModule.Instance.GetTempLevelSaveData();
                if (pod == null)
                {
                    return;
                }
                string json = JsonHelper.SerializeObject(pod);
                string path = "/ToolApp/Script/Editor/LevelMapEditor/Config/TempLvSave.json";
                File.WriteAllText(Application.dataPath + path, json);
                AssetDatabase.Refresh();
                Debug.Log("保存完毕");
            }
        }

        [MenuItem("ToolApp/关卡编辑器/保存/清除存档", false, 9)]
        private static void DeleteTempSave()
        {
            if (EditorUtility.DisplayDialog("警告", "确定要删除存档吗？", "确定", "取消"))
            {
                if (File.Exists(tempSavePath))
                {
                    File.Delete(tempSavePath);
                }
                AssetDatabase.Refresh();
                Debug.Log("清除完毕");
            }
        }

        //[MenuItem("ToolApp/修改GamePlay配置兼容新Rect格式")]
        static void CompatibleWithNewRect()
        {
            TextAsset text = Selection.activeObject as TextAsset;
            if (text != null)
            {
                string content = text.text;
                string pattern = @"""rect"":\s*""(?<x>-?\d+),\s*(?<y>-?\d+),\s*(?<width>-?\d+),\s*(?<height>-?\d+)""";
                string replacement = @"""rect"": {
            ""X"": ${x},
            ""Y"": ${y},
            ""Width"": ${width},
            ""Height"": ${height},
            ""IsEmpty"": false
          }";
                string result = Regex.Replace(content, pattern, replacement);

                string path = AssetDatabase.GetAssetPath(text);
                string root = Application.dataPath.Replace("/Assets", "/");
                System.IO.File.WriteAllText(root + path, result);
            }
        }

        // 该类是runtime临时类，新增MenuItem需要加Editor宏，不然打包失败
#endif

        private FakeDataCenter()
        {
            levelPOD = CreateLevelPOD();
            //开发临时存档
            if (File.Exists(tempSavePath))
            {
                string json = File.ReadAllText(tempSavePath);
                levelSavePOD = JsonHelper.DeserializeJson<LevelSavePOD>(json);
            }
            else
            {
                levelSavePOD = CreateLevelSavePOD();
            }
        }

        private CreateLevelPOD CreateLevelPOD()
        {
            CreateLevelPOD pod = new CreateLevelPOD();
            pod.id = 1;
            pod.cid = levelCid;
            pod.randomSeed = DateTime.Now.Millisecond / 1000;
            pod.isLocal = isLocalLevel;
            pod.hostPlayerId = playerId;
            return pod;
        }

        public LogicPlayerPOD CreateLogicPlayerPOD()
        {
            LogicPlayerPOD playerPod = new LogicPlayerPOD();
            playerPod.pid = playerId;
            playerPod.gameServerId = gameServerId;

            playerPod.name = "Genius boy";
            playerPod.level = 1;
            playerPod.exp = 0;
            playerPod.avatar = 1;
            playerPod.avatarFrame = 1;

            playerPod.unsafe_heroes = CreateHeros();
            playerPod.formation = new FormationPOD();
            {
                playerPod.formation.formId = 1;
                playerPod.formation.formName = "编队1";
                playerPod.formation.captainHeroCid = 100201;
                playerPod.formation.heroes[1] = new FormationHeroPOD()
                {
                    id = 1,
                    cid = 100201
                };
                playerPod.formation.heroes[2] = new FormationHeroPOD()
                {
                    id = 1,
                    cid = 100301
                };
            }
            return playerPod;
        }

        private List<HeroPOD> CreateHeros()
        {
            List<HeroPOD> heros = new List<HeroPOD>();
            heros.Add(CreateHero(1, 100201, 1, 0, 0));
            heros.Add(CreateHero(2, 100301, 1, 0, 0));
            return heros;
        }

        private HeroPOD CreateHero(int id, int cid, int level, int x, int y)
        {
            var rConfig = TableCenter.hero.Get(cid);
            var rAttrType = new List<int>(rConfig.AttType);
            var rAttrValue = new List<int>(rConfig.AttValue);
            int[] attrs = new int[TableCenter.attribute.DataList.Count + 1];
            Dictionary<int, int> skills = new Dictionary<int, int>();
            foreach (var skillCid in rConfig.DefaultSkill)
            {
                skills[skillCid] = 1;
            }
            for (int i = 0; i < rAttrType.Count; i++)
            {
                attrs[rAttrType[i]] = rAttrValue[i];
            }
            HeroPOD hero = new HeroPOD();
            hero.id = id;
            hero.cid = cid;
            hero.awakenLevel = 0;
            hero.level = level;
            hero.exp = 0;
            hero.skinCid = rConfig.HeroSkinIds[0];
            hero.star = 1;
            hero.attrs = attrs;
            hero.unsafe_skills = skills;
            return hero;
        }

        private LevelSavePOD CreateLevelSavePOD()
        {
            return new LevelSavePOD();
        }
    }
}